package hr.fer.zesoi.neumre;

import hr.fer.zesoi.neumre.logic.TetrisBoard;
import hr.fer.zesoi.neumre.tetriminos.Tetrimino;
import hr.fer.zesoi.neumre.tetriminos.common.Location;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JComponent;

public class TetrisBirhtplaceComponent extends JComponent {

	private static final long serialVersionUID = 6715549686225118200L;

	private Tetrimino tetrimino;

	private int tetriminoLength;

	private int tetriminoHeight;

	private int minRelX;

	private int minRelY;

	private int boardRows;

	private int boardCols;

	public TetrisBirhtplaceComponent(int boardRows, int boardCols) {

		this.boardRows = boardRows;
		this.boardCols = boardCols;
	}

	public void setTetrimino(Tetrimino tetrimino) {

		this.tetrimino = tetrimino;

		if (tetrimino != null) {

			int maxX = 0;
			int maxY = 0;

			minRelX = 0;
			minRelY = 0;

			for (int pixel = 0; pixel < 4; pixel++) {
				Location pixelLoc = tetrimino.getPixelRelLocs()[pixel];

				if (pixelLoc.getPosX() > maxX)
					maxX = pixelLoc.getPosX();
				if (pixelLoc.getPosY() > maxY)
					maxY = pixelLoc.getPosY();

				if (pixelLoc.getPosX() < minRelX)
					minRelX = pixelLoc.getPosX();
				if (pixelLoc.getPosY() < minRelY)
					minRelY = pixelLoc.getPosY();
			}

			this.tetriminoHeight = maxY - minRelY + 1;
			this.tetriminoLength = maxX - minRelX + 1;
		}

		this.repaint();
	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponents(g);

		g.setColor(Color.lightGray);
		g.fillRect(0, 0, this.getSize().width, this.getSize().height);

		if (this.tetrimino != null) {

			g.setColor(Color.black);

			int pixelWidth = (int) Math.floor(this.getSize().width / boardCols);
			int pixelHeight = (int) Math.floor(this.getSize().height
					/ boardRows);

			int colSpacing = Math.max(1, pixelWidth / 25);
			int rowSpacing = Math.max(1, pixelHeight / 25);

			int xBreak = (int) Math
					.floor((double) (this.getSize().width - tetriminoLength
							* pixelWidth) / 2);
			int yBreak = (int) Math
					.floor((double) (this.getSize().height - tetriminoHeight
							* pixelHeight) / 2);

			for (int pixel = 0; pixel < 4; pixel++) {

				int posX = xBreak
						+ (tetrimino.getPixelRelLocs()[pixel].getPosX() - minRelX)
						* pixelWidth;
				int posY = this.getSize().height
						- (yBreak + (tetrimino.getPixelRelLocs()[pixel]
								.getPosY() - minRelY + 1)
								* pixelHeight);

				g.fillRect(posX + colSpacing, posY + rowSpacing, pixelWidth - 2
						* colSpacing, pixelHeight - 2 * rowSpacing);
			}
		}
	}
}
